// pages/account/account.js
Page({
  data: {
    openid: null,
    accounts: [],
    count: 0,
    total: 0,
    fuzai: 0,
    loading: false
  },

  // 获取用户openid
  getOpenid: function() {
    const that = this;
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        const openid = res.result.openid;
        console.log('openid:'+openid)
        that.setData({ openid });
        that.loadAccount(openid);
      },
      fail: err => {
        console.error('获取openid失败:', err);
        wx.showToast({ title: '用户认证失败', icon: 'none' });
      }
    });
  },

  // 加载账户数据
  loadAccount: function(openid) {
    if (this.data.loading) return;
    this.setData({ loading: true });
    const db = wx.cloud.database();
    db.collection('account')
      .where({ _openid: openid })
      .orderBy('createTime', 'desc')
      .get()
      .then(res => {
        console.log(res)
        const accounts = res.data;
        // 分离正负金额
        const assets = accounts.filter(item => item.balance >= 0);
        const debts = accounts.filter(item => item.balance < 0);
        // 计算资产总额（正数）
        const total = assets.reduce((sum, item) => 
        sum + parseFloat(item.balance || 0), 0);
        // 计算负债总额（负数取绝对值）
        const debtTotal = debts.reduce((sum, item) => 
        sum + Math.abs(parseFloat(item.balance || 0)), 0);
        this.setData({
          accounts: accounts,
          count: accounts.length,
          total: total.toFixed(2),
          fuzai: debtTotal.toFixed(2)
        });
      })
      .catch(err => {
        console.error('数据库查询失败:', err);
        wx.showToast({ title: '数据加载失败', icon: 'none' });
      })
      .finally(() => {
        this.setData({ loading: false });
      });
  },

  // 页面显示时触发
  onShow: function() {
    this.getOpenid();
  },

  // 跳转新建账户页
  add: function(e) {
    wx.navigateTo({
      url: `../createAccount/createAccount`
    });
  },

  // 查看账户详情
  seeDetail: function(e) {
    const { id, balance } = e.currentTarget.dataset;
    if (!id) {
      return console.error('缺少必要参数',e.currentTarget.dataset);
    }
    wx.navigateTo({
      url: `../accountDetail/accountDetail?id=${id}&balance=${balance}`
    });
  }
});
